package com.startest.sms.config;


import com.startest.sms.pojo.User;
import com.startest.sms.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by cly on 2019/1/9.
 */

public class PhoneRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        return null;
    }

    /**
     * 身份认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String phone = null;
        if(token instanceof PhoneToken){
            phone = (String) token.getPrincipal();
        }else {
            return null;
        }
        User user = userService.selectUserByPhone(phone);
        if(user!=null){
            return new SimpleAuthenticationInfo(phone,user.getPhone(),this.getName());
        }
        return null;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof PhoneToken;
    }
}
